#ifdef _WIN32

#include "win32_StartupEnvironment.h"
#include "Format.h"
#include "Win32Exception.h"
#include "UnicodeString.h"
#include <vector>
#include <Windows.h>
#include <ShellAPI.h>

using namespace std;

namespace lhcutils
{

StringPtr unexpectedErrorMessage = ustr("Something has gone terribly wrong");

#define THROW_UNEXPECTED_WIN32 throw Win32Exception(unexpectedErrorMessage, __FILE__, __LINE__)

// Can throw Win32Exception if something goes wrong.
vector<StringPtr> GetUnicodeArgv();

// Can throw Win32Exception, Exception if something goes wrong.
StringPtr GetInvocationName();

lhcutils::StartupEnvironment GetStartupEnvironment()
{
	vector<StringPtr> unicodeArgv = GetUnicodeArgv();
	StringPtr invocationName = GetInvocationName();
}

vector<StringPtr> GetUnicodeArgv()
{
	vector<StringPtr> unicodeArgv;

	int wArgc;
	LPWSTR* wArgv = CommandLineToArgvW(GetCommandLineW(), &wArgc);

	if(wArgv == NULL)
	{
		THROW_UNEXPECTED_WIN32;
	}

	for(int i = 0; i < wArgc; i++)
	{
		// do something with wArgv[i]
		StringPtr unicodeArg = ustr(static_cast<void*>(wArgv[i]), lhcutils::encodings::Utf16);
		unicodeArgv.push_back(unicodeArg);
	}

	HLOCAL rc = LocalFree(wArgv);
	if(rc == NULL)
	{
		THROW_UNEXPECTED_WIN32;
	}

	return unicodeArgv;
}

StringPtr GetInvocationName()
{
	const DWORD MaxCharsToTry = 65536; // Double the 32768 limit just to be safe
	
	DWORD bufferSizeInWChars = 1024;
	vector<wchar_t> nameBuffer(bufferSizeInWChars);
	bool nameFit = false;
	DWORD charsInName; // not counting null character

	while(!nameFit && bufferSizeInWChars <= MaxCharsToTry)
	{
		charsInName = GetModuleFileNameW(NULL, &(nameBuffer[0]), bufferSizeInWChars);
		if(charsInName == 0)
		{
			THROW_UNEXPECTED_WIN32;
		}
		else if(charsInName == bufferSizeInWChars)
		{
			// not enough space in the buffer
			bufferSizeInWChars *= 2;
			nameBuffer.resize(bufferSizeInWChars);
		}
		else
		{
			nameFit = true;
		}
	}

	if(nameFit)
	{
		return winstr(&(nameBuffer[0]), charsInName);
	}
	else
	{
		THROW_BASIC(format(*ustr("{0}: Could not figure out my own name."), *unexpectedErrorMessage));
	}
}

}

#endif

/*
 Copyright 2011 Greg Najda

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
